import {useState} from "react";
import utils from "@/utils";
import {Address} from "@/api/methods/address/index.type";

interface UseOrderReturn {
  // 地址列表
  addresses: Address.Res.Data | undefined
  // 设置地址
  setAddresses: (addresses: Address.Res.Data) => void
  // 处理地址数据
  handleAddressData: (data: any) => void
  // 获取默认地址
  getDefaultAddress: () => void
}

/**
 * 用于处理订单的逻辑
 */
export const useCommon = (): UseOrderReturn => {
  const [addresses, setAddresses] = useState<Address.Res.Data>();
  // 处理地址数据
  const handleAddressData = (data: any[]) => {
    const province_list: Record<string, string> = {};
    const city_list: Record<string, string> = {};
    const county_list: Record<string, string> = {};
    data.forEach((province) => {
      // 处理省份数据
      const provinceCode = province.code.padEnd(6, "0");
      province_list[provinceCode] = province.name;

      // 处理城市数据
      if (province.regionList && province.regionList.length > 0) {
        province.regionList.forEach((city: any) => {
          const cityCode = city.code.padEnd(6, "0");
          city_list[cityCode] = city.name;

          // 处理区县数据
          if (city.regionList && city.regionList.length > 0) {
            city.regionList.forEach((county: any) => {
              const countyCode = county.code.padEnd(6, "0");
              county_list[countyCode] = county.name;
            });
          }
        });
      }
    });

    return {
      province_list,
      city_list,
      county_list,
    };
  }

  // 获取默认地址
  const getDefaultAddress = () => {
    utils.$apis
      .getAddressList({
        page: 1,
        take: 100,
      })
      .then((res) => {
        if (res.data.length > 0) {
          const defaultAddress = res.data.find((item) => item.isDefault);
          if (defaultAddress) {
            setAddresses(defaultAddress);
            console.log(defaultAddress, "defaultAddress");
          }
        }
      });
  }
  return {
    handleAddressData,
    getDefaultAddress,
    addresses,
    setAddresses
  };
};
